package com.dabai.dbutils.utils;

import android.Manifest;
import android.app.AppOpsManager;
import android.app.KeyguardManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationManagerCompat;

import com.bumptech.glide.util.Util;

import java.util.List;

/**
 * 其他权限帮助类
 *
 * @author BAI
 */
public class OtherPermissionUtils {


    @RequiresApi(api = Build.VERSION_CODES.O)
    public static boolean checkInstallApkPermission(Context context){
        return context.getPackageManager().canRequestPackageInstalls();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void requestInstallApkPermission(Context context){
        Uri packageURI = Uri.parse("package:"+context.getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
        context.startActivity(intent);
    }


    /**
     * 检查所有文件权限管理应用
     *
     * @param context 上下文
     * @return boolean
     */
    @RequiresApi(api = Build.VERSION_CODES.R)
    public static boolean checkManageAllFilePermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            int noteOp = -1;
            try {
                AppOpsManager opsManager = context.getSystemService(AppOpsManager.class);
                noteOp = opsManager.noteOp("android:manage_external_storage", AppUtils.getUid(context), context.getPackageName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return noteOp == AppOpsManager.MODE_ALLOWED;
        }
        return false;
    }


    /**
     * 请求管理所有文件权限
     *
     * @param context 上下文
     */
    @RequiresApi(api = Build.VERSION_CODES.R)
    public static void requestManageAllFilePermission(Context context) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }


    /**
     * 屏幕 是否有密码 (屏幕锁)
     *
     * @param context 上下文
     * @return boolean
     */
    public static boolean hasScreenLocker(Context context) {
        KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        return km.isKeyguardSecure();
    }


    /**
     * app使用状态的权限
     *
     * @param context 上下文
     * @return boolean
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    public static boolean isUsingStatePermissions(Context context) {
        long endTime = System.currentTimeMillis();
        UsageStatsManager usageStatsManager;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            usageStatsManager = (UsageStatsManager) context.getApplicationContext().getSystemService(Context.USAGE_STATS_SERVICE);
            List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, 0, endTime);
            if (queryUsageStats == null || queryUsageStats.isEmpty()) {
                return false;
            }
        }

        return true;
    }


    /**
     * 开放使用状态的权限
     *
     * @param context 上下文
     */
    public static void openUsingStatePermissions(Context context) {
        try {
            Intent intent = new Intent("android.settings.USAGE_ACCESS_SETTINGS",
                    Uri.parse("package:" + context.getPackageName()));
            context.startActivity(intent);
        } catch (Exception e) {
            DabaiUtils.toMyAppInfo(context);
        }
    }


    /**
     * 是否有浮动窗口的权限
     *
     * @param context 上下文
     * @return boolean
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static boolean isWriteSettingsPermissions(Context context) {
        return Settings.System.canWrite(context);
    }

    /**
     * 浮动窗口权限界面
     *
     * @param context 上下文
     */
    public static void openWriteSettingsPermissions(Context context) {
        try {
            Intent intent = new Intent("android.settings.action.MANAGE_WRITE_SETTINGS",
                    Uri.parse("package:" + context.getPackageName()));
            context.startActivity(intent);
        } catch (Exception e) {
            DabaiUtils.toMyAppInfo(context);
        }
    }


    /**
     * 是否有浮动窗口的权限
     *
     * @param context 上下文
     * @return boolean
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static boolean isFloatingWindowPermissions(Context context) {
        return Settings.canDrawOverlays(context);
    }

    /**
     * 浮动窗口权限界面
     *
     * @param context 上下文
     */
    public static void openFloatingWindowPermissions(Context context) {
        try {
            Intent intent = new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION",
                    Uri.parse("package:" + context.getPackageName()));
            context.startActivity(intent);
        } catch (Exception e) {
            DabaiUtils.toMyAppInfo(context);
        }
    }

    /**
     * 是否启用通知
     *
     * @param context 上下文
     * @return boolean
     */
    public static boolean isNotificationsPermissions(Context context) {
        return NotificationManagerCompat.from(context).areNotificationsEnabled();
    }


    /**
     * 弹窗跳转通知权限界面
     * 8.0以上会跳转到NOTIFICATION_SETTINGS
     * 8.0以下会跳转AppInfo
     *
     * @param context 上下文
     */
    public static void openNotificationsPermissions(Context context) {
        try {
            Intent intent = new Intent();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");

                //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
                intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
                intent.putExtra("android.provider.extra.CHANNEL_ID", context.getApplicationInfo().uid);

                //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
                intent.putExtra("app_package", context.getPackageName());
                intent.putExtra("app_uid", context.getApplicationInfo().uid);
                context.startActivity(intent);
            } else {
                DabaiUtils.toMyAppInfo(context);
            }
        } catch (Exception e) {
            Log.d("DBTAG", "jumpToNotAccessInterface: " + e.getMessage());
            DabaiUtils.toMyAppInfo(context);
        }

    }
}

